package com.xiaowu.web.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.xiaowu.commons.utils.CommonUtils;
import com.xiaowu.commons.utils.DateUtils;

/**
 * 公用
 * @author WH
 *
 */
@Controller
@RequestMapping("common")
public class CommonController {

	/**
	 * 上传文件
	 * @param file 文件
	 * @param saveCatalog 目录
	 * @return
	 */
	@ResponseBody
	@RequestMapping("uploadFile")
	public String uploadFile(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request,String saveCatalog){
		
		//项目路径
		String productPath = request.getSession().getServletContext().getRealPath("/");
		//文件路径
		String filePath = "upload/"+saveCatalog+"/";
		//保存的目录路径
		String path = productPath + filePath;
		
		//判断文件是否为空 
		if(!file.isEmpty()){
			 //上传文件名
			 String fileName = file.getOriginalFilename();
			 //后缀
			 String suffix = fileName.substring(fileName.lastIndexOf(".")); 
			 //得到时间
			 String time = DateUtils.getCurren("yyyyMMddHHmmss");
			 //使用时间和UUID来生成文件名
			 String saveFileName  = time + CommonUtils.getUUID() + suffix;
			 System.out.println(suffix);
			File targetFile = new File(path, saveFileName);  
			 //判断文件是否存在，不存在则创建
			if(!targetFile.exists()) targetFile.mkdirs();  
	        try {
	        	//保存  
				file.transferTo(targetFile);
				return filePath+saveFileName;
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}  
		}
		return "false";
	}
	
}
